#!/usr/bin/env python3
import os
import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
from sensors.max31865_adc import SerialTemperatureReader
from camera.imx219_cam import Imx219Camera
from camera.tf25a_ir import Tf25aCamera

os.environ["DISPLAY"] = ":0"

def put_text_pil(frame, text, position=(10, 30), font_size=32, color=(255,0,0)):
    img_pil = Image.fromarray(frame)
    draw = ImageDraw.Draw(img_pil)
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", font_size)
    except:
        font = ImageFont.load_default()
    draw.text(position, text, font=font, fill=color)
    return np.array(img_pil)

def main():
    temp_reader = SerialTemperatureReader('/dev/ttyS0')
    if not temp_reader.connect():
        print("[WARNING] 串口连接失败，温度显示将使用默认值")
    
    cam0 = Imx219Camera("/dev/video22", name="IMX219-0")
    cam1 = Imx219Camera("/dev/video31", name="IMX219-1")
    ir_cam = Tf25aCamera("/dev/video40", name="TF25A")

    if not cam0.open_v4l2():  
        print("[ERROR] 摄像头打开失败")
        return
    if not cam1.open_v4l2():  
        print("[ERROR] 摄像头打开失败")
        return
    if not ir_cam.open():  
        print("[ERROR] 摄像头打开失败")
        return

    print("[INFO] 开始采集，按 'q' 退出或 Ctrl+C 停止")
    cv2.namedWindow("Camera View", cv2.WND_PROP_FULLSCREEN)
    cv2.setWindowProperty("Camera View", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

    try:
        while True:
            frame0 = cam0.read()
            frame1 = cam1.read()
            frame_ir = ir_cam.read()

            temperature = temp_reader.read_temperature()
            if temperature is not None:
                temp_text = f"Temperature: {temperature:.2f} °C"
            else:
                temp_text = f"Temperature: -- °C"

            if frame0 is not None:
                frame0_resized = cv2.resize(frame0, (960, 540))
                frame0_resized = put_text_pil(frame0_resized, temp_text)
            if frame1 is not None:
                frame1_resized = cv2.resize(frame1, (960, 540))
                frame1_resized = put_text_pil(frame1_resized, temp_text)
            if frame_ir is not None:
                frame_ir_resized = cv2.resize(frame_ir, (960, 540))
                frame_ir_resized = put_text_pil(frame_ir_resized, temp_text)

            top_row = np.hstack((frame0_resized, frame1_resized))  
            bottom_row = np.hstack((frame_ir_resized, frame_ir_resized))

            full_frame = np.vstack((top_row, bottom_row))

            cv2.imshow("Camera View", full_frame)
            if temperature is not None:
                print(f"当前温度: {temperature:.2f} °C", end="\r")
            else:
                print(f"当前温度：-- °C", end='\r')

            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                print("[INFO] 用户按下 'q'，停止采集")
                break

    except KeyboardInterrupt:
        print("\n[INFO] 用户中断，停止采集")
    except Exception as e:
        print(f"[ERROR] 发生错误: {e}")

    finally:
        temp_reader.release()
        cam0.release()
        cam1.release()
        ir_cam.release()
        cv2.destroyAllWindows()


if __name__ == "__main__":
    main()
